package com.ly.emp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.core.bean.R;
import com.ly.common.core.bean.dto.CommonBatchUpdateDTO;
import com.ly.emp.bean.dto.HubTeamDTO;
import com.ly.emp.constant.EmpConstants;
import com.ly.emp.constant.EmpErrorConstants;
import com.ly.emp.entity.EpmBaseRel;
import com.ly.emp.entity.HubTeamResultEvaluate;
import com.ly.emp.mapper.HubTeamResultEvaluateMapper;
import com.ly.emp.service.IEmpCommonService;
import com.ly.emp.service.IHubTeamResultEvaluateService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 考核结果-综合评价-impl
 *
 * @author luoyun
 * @Date: 2025-05-20
 */
@Service
@RequiredArgsConstructor
public class HubTeamResultEvaluateServiceImpl extends ServiceImpl<HubTeamResultEvaluateMapper, HubTeamResultEvaluate> implements IHubTeamResultEvaluateService {

    private final IEmpCommonService teamCommonService;

    @Override
    public R getId(String id) {
        HubTeamResultEvaluate entity = this.getById(id);
        if (entity == null) {
            return R.fail("未找到对应数据");
        }
        return R.ok(entity);
    }

    @Override
    public R getList(HubTeamResultEvaluate entity) {
        String orgCode = entity.getOrgCode();
        if(StrUtil.isBlank(orgCode)){
            return R.fail(EmpErrorConstants.NO_TEAM);
        }
        List<String> isIntensificationList = teamCommonService.getIsIntensificationListByOrgCode(orgCode);
        List<HubTeamResultEvaluate> list = this.list(
                new LambdaQueryWrapper<HubTeamResultEvaluate>()
                        .in(HubTeamResultEvaluate::getOrgCode,isIntensificationList)
                        .eq(StrUtil.isNotBlank(entity.getPeriodCode()), HubTeamResultEvaluate::getPeriodCode,entity.getPeriodCode())
                        .eq(StrUtil.isNotBlank(entity.getSuitUnit()),HubTeamResultEvaluate::getSuitUnit,entity.getSuitUnit())
                        .likeRight(StrUtil.isNotBlank(entity.getFinalScoreStatus()),HubTeamResultEvaluate::getFinalScore, entity.getFinalScoreStatus())
                        .orderByAsc(HubTeamResultEvaluate::getOrgCode)
                        .orderByDesc(HubTeamResultEvaluate::getSysCreateDate)
                        .orderByAsc(HubTeamResultEvaluate::getDisplayOrder)
        );
        return R.ok(list);
    }

    @Override
    public R getPage(HubTeamResultEvaluate entity, Page<HubTeamResultEvaluate> page) {
        String orgCode = entity.getOrgCode();
        if(StrUtil.isBlank(orgCode)){
            return R.fail(EmpErrorConstants.NO_TEAM);
        }
        List<String> isIntensificationList = teamCommonService.getIsIntensificationListByOrgCode(orgCode);
        IPage<HubTeamResultEvaluate> pageList = this.page(page,
                new LambdaQueryWrapper<HubTeamResultEvaluate>()
                        .in(HubTeamResultEvaluate::getOrgCode,isIntensificationList)
                        .eq(StrUtil.isNotBlank(entity.getPeriodCode()), HubTeamResultEvaluate::getPeriodCode,entity.getPeriodCode())
                        .like(StrUtil.isNotBlank(entity.getPsnName()), HubTeamResultEvaluate::getPsnName,entity.getPsnName())
                        .orderByAsc(HubTeamResultEvaluate::getOrgCode)
                        .orderByDesc(HubTeamResultEvaluate::getSysCreateDate)
                        .orderByAsc(HubTeamResultEvaluate::getDisplayOrder));
        return R.ok(pageList);
    }

    @Override
    public R add(HubTeamResultEvaluate entity) {
        boolean flag = this.save(entity);
        return flag ? R.ok(true, "创建成功") : R.fail("创建失败");
    }

    @Override
    public R edit(HubTeamResultEvaluate entity) {
        boolean flag = this.updateById(entity);
        return flag ? R.ok(true, "修改成功") : R.fail("修改失败");
    }

    @Override
    public R delete(String id) {
        boolean flag = this.removeById(id);
        return flag ? R.ok(true, "删除成功") : R.fail("删除失败");
    }

    @Override
    public R deleteBatch(String ids) {
        boolean flag = this.removeByIds(Arrays.asList(ids.split(",")));
        return flag ? R.ok(true, "批量删除成功") : R.fail("批量删除失败");
    }

    @Override
    public R updateBatch(CommonBatchUpdateDTO<HubTeamResultEvaluate> dto) {
        List<HubTeamResultEvaluate> datas = dto.getDatas();
        boolean flag = this.saveOrUpdateBatch(datas);
        return flag ? R.ok(true, "批量修改成功") : R.fail("批量修改失败");
    }

    @Override
    public R initResultEvaluate(HubTeamDTO dto) {
        String orgCode = dto.getOrgCode();
        List<String> isIntensificationListByOrgCode = teamCommonService.getIsIntensificationListByOrgCode(orgCode);
        //已经存在的综合评价列表
        List<HubTeamResultEvaluate> existsEvaluateList = this.list(
                new LambdaQueryWrapper<HubTeamResultEvaluate>()
                        .eq(HubTeamResultEvaluate::getPeriodCode,dto.getPeriodCode())
                        .in(HubTeamResultEvaluate::getOrgCode, isIntensificationListByOrgCode)
        );
        //班组对应员工列表
        List<EpmBaseRel> baseRelList = teamCommonService.getBaseRelListByOrgCode(null, orgCode);
        if (CollUtil.isEmpty(baseRelList)) {
            return R.fail(EmpErrorConstants.TEAM_STAFF_ERROR);
        }
        //根据工号排除掉已经初始化了的人员
        List<EpmBaseRel> noAddList = CollUtil.isEmpty(existsEvaluateList) ? baseRelList:
                baseRelList.stream().filter(n -> existsEvaluateList.stream().map(HubTeamResultEvaluate::getPsnNum).noneMatch(m -> Objects.equals(n.getPsnNum(), m))).collect(Collectors.toList());
        List<HubTeamResultEvaluate> addList = new ArrayList<>();
        if(CollUtil.isNotEmpty(noAddList)){
            noAddList.stream().forEach(n -> {
                HubTeamResultEvaluate add = BeanUtil.copyProperties(n,HubTeamResultEvaluate.class,new String[]{"seqKey"});
                add.setPeriodCode(dto.getPeriodCode());
                add.setStatus(Integer.valueOf(EmpConstants.RESULT_STATUS_SUMMARY));
                addList.add(add);
            });
        }else{
            return R.fail(EmpErrorConstants.NO_INIT_SUMMERY_DATA);
        }
        boolean b = this.saveOrUpdateBatch(addList);
        return R.ok(true,"初始化成功");
    }
}
